package com.xhwy.service.impl;

import com.xhwy.entity.OrderDetail;
import com.xhwy.entity.Product;
import com.xhwy.entity.ProductType;
import com.xhwy.mapper.OrderDetailMapper;
import com.xhwy.mapper.ProductMapper;
import com.xhwy.mapper.ProductTypeMapper;
import com.xhwy.mapper.UserMapper;
import com.xhwy.service.StatisticsService;
import com.xhwy.vo.R;
import com.xhwy.vo.admin.PieDataVo;
import com.xhwy.vo.admin.TurnoverChartVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class StatisticsServiceImpl implements StatisticsService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductTypeMapper productTypeMapper;

    /**
     * 获取数据总览
     * 1.用户总数
     * 2.今日注册用户数
     * 3.今日营业额
     * 4.最近一周营业额
     * 5.最近一月营业额
     * @return
     */
    @Override
    public R synopsis() {
        //用户总数
        Integer totalUserCount = userMapper.getTotalUserCount();
        //今日用户数量
        Integer todayUserCount =userMapper.getTodayUserCount();
        //今日营业额
        Double todayTurnover = orderDetailMapper.getTodayTurnover();
        //近一周营业额
        Double weekTurnover = orderDetailMapper.getWeekTurnover();
        //近一月营业额
        Double monthTurnover = orderDetailMapper.getMonthTurnover();

        R r = R.ok("数据查询成功");
        r.put("totalUserCount", totalUserCount);
        r.put("todayUserCount", todayUserCount);
        r.put("todayTurnover", todayTurnover);
        r.put("weekTurnover", weekTurnover);
        r.put("monthTurnover", monthTurnover);

        return r;
    }

    /**
     * 获取今年的每月营业额
     *
     * @return
     */
    @Override
    public R monthlyTurnover() {
        Map<String, Object> data = new HashMap<>();
        TurnoverChartVo turnoverChartVo = new TurnoverChartVo();
        String[] numberMonth = turnoverChartVo.getNumberMonth();
        Double[] monthlyTurnoverData = turnoverChartVo.getMonthlyTurnoverData();
        //获取今年的第一天
        Calendar startCalendar = Calendar.getInstance();
        Calendar endCalendar = Calendar.getInstance();
        Calendar curCalendar = Calendar.getInstance();
        //存储年份
        data.put("year", curCalendar.get(Calendar.YEAR));
        //重置时间到1970-1-1
        startCalendar.clear();
        //设置年份为今年
        startCalendar.set(Calendar.YEAR,curCalendar.get(Calendar.YEAR));

        //获取今年第一天的日期，用来查询订单的条件
        Date firstDayOfYear = startCalendar.getTime();
        Timestamp startDateTime = new Timestamp(firstDayOfYear.getTime());
        //获取大于提供的日期的订单
        List<OrderDetail> orderDetailList = orderDetailMapper.getOrderByTimestamp(startDateTime);

        //设置结束的日历为开始日历的下一个月
        endCalendar.setTime(firstDayOfYear);
        endCalendar.add(Calendar.MONTH, 1);

        while (true){
            //获取两者的时间戳
            long startTimestamp = startCalendar.getTime().getTime();
            long endTimestamp = endCalendar.getTime().getTime();
            double monthlyTurnover = 0.0;
            //循环月份的月营业额
            for (OrderDetail orderDetail : orderDetailList) {
                //判断付款时间
                long paymentTimestamp = orderDetail.getPaymentTime().getTime();
                //判断付款时间是否处在循环月份
                if(paymentTimestamp>= startTimestamp && paymentTimestamp < endTimestamp){
                    //转换精度更准确的BigDecimal类进行计算
//                    monthlyTurnover += orderDetail.getTotalPayment();
                    BigDecimal monthlyTurnoverBigDecimal = new BigDecimal(Double.toString(monthlyTurnover));
                    BigDecimal totalPaymentBigDecimal = new BigDecimal(Double.toString(orderDetail.getTotalPayment()));
                    monthlyTurnover = monthlyTurnoverBigDecimal.add(totalPaymentBigDecimal).doubleValue();
                }
            }
            //添加数据到数组中
            for (int i = 0; i < numberMonth.length; i++) {
                if(Integer.parseInt(numberMonth[i]) == startCalendar.get(Calendar.MONTH)  + 1){
                    monthlyTurnoverData[i] = monthlyTurnover;
                }
            }
            //修改日历
            startCalendar.add(Calendar.MONTH, 1);
            endCalendar.add(Calendar.MONTH, 1);
            //获取开始月份，如果大于当前系统月份，跳出循环
            if (startCalendar.get(Calendar.MONTH) > curCalendar.get(Calendar.MONTH)) break;
        }
        //存储整个营业额图表的视图对象
        data.put("turnoverChartVo", turnoverChartVo);
        R r = R.ok();
        r.setData(data);
        return r;
    }

    /**
     * 销量在商品类型中的分布
     *
     * @return
     */
    @Override
    public R salesDistribution() {
        //获取全部商品信息
        List<Product> productList = productMapper.queryAllByLimit(null,null);
        //获取全部商品类型信息
        List<ProductType> productTypeList = productTypeMapper.queryAll(null, null);

        //根据商品类型id对商品集合进行分组
        Map<Integer, List<Product>> productMap = productList.stream().collect(Collectors.groupingBy(Product::getProductTypeId));

        List<PieDataVo> pieDataVos = new ArrayList<>();
        for (ProductType productType : productTypeList) {
            //创建Vo视图对象
            PieDataVo pieDataVo = new PieDataVo();
            //获取该类型的商品
            List<Product> products = productMap.get(productType.getProductTypeId());
            pieDataVo.setName(productType.getProductTypeName());
            //获取该分类中所有商品的总销量
            int totalSalesVolume = 0;
            for (Product pro : products) {
                totalSalesVolume += pro.getSalesVolume();
            }
            //设置销量信息
            pieDataVo.setValue(totalSalesVolume);
            //添加到数据集合中
            pieDataVos.add(pieDataVo);
        }

        return R.ok("数据查询成功").put("pieDataVos", pieDataVos);
    }
}
